<template>
  <div :class="['navbar', { 'hidden': isHidden }]">
    <div class="site-header-in">
      <div class="header-banner-left">
        <div id="ym-menu" class="ym-menu">
          <div id="top-menu" class="top-menu">
            <ul id="top-menu-ul" class="top-menu-ul">
              <li>
                <el-image src="./static/maotou.png" class="logo"/>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="cosplay" to="/">
                  <span>
                    <el-icon class="custom-icon">
                      <svg x="1710869517240" class="icon" viewBox="0 0 1024 1024" version="1.1"
                           xmlns="http://www.w3.org/2000/svg" p-id="52279" width="16" height="16">
                        <path
                            d="M914.5344 463.104l-76.288-66.304c-1.3824-1.6384-3.0208-3.1232-4.864-4.2496l-288.8704-251.136c-19.1488-16.64-48.0256-16.64-67.1744 0L188.416 392.5504c-1.8432 1.1264-3.4816 2.6112-4.864 4.2496l-76.288 66.304a20.44416 20.44416 0 0 0-1.9968 28.8768 20.44416 20.44416 0 0 0 28.8768 1.9968l44.4928-38.7072v347.648c0 50.7904 41.3184 92.16 92.16 92.16h480.2048c50.7904 0 92.16-41.3696 92.16-92.16v-347.648l44.544 38.7072c3.8912 3.3792 8.6528 5.0176 13.4144 5.0176 5.7344 0 11.4176-2.4064 15.4624-7.0656 7.424-8.448 6.5024-21.4016-2.048-28.8256zM493.4656 796.672H354.2528c-31.0784 0-56.32-25.2416-56.32-56.32v-196.5568c0-14.1312 11.4688-25.6 25.6-25.6s25.6 11.4688 25.6 25.6v196.5568c0 2.816 2.304 5.12 5.12 5.12h139.2128c14.1312 0 25.6 11.4688 25.6 25.6s-11.4688 25.6-25.6 25.6z"
                            fill="#13227a" p-id="52280"></path>
                      </svg>
                    </el-icon>
                    <span class="icon-text" style="margin-left: 0">首页</span>
                  </span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="cosplay" to="/cosplay">
                  <span style="margin-left: 0">合集</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="dujia" to="/dujia">
                  <span style="margin-left: 0">独家</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="order" to="/order">
                  <span style="margin-left: 0">收藏家</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="guanhua" to="/guanhua">
                  <span style="margin-left: 0">在线看</span>
                </router-link>
              </li>

            </ul>
          </div>
        </div>
        <div class="mobile-menu" @click="toggletagpages">
          <span>
            <el-icon>
              <Operation/>
            </el-icon>
          </span>
        </div>
        <el-drawer v-model="tagpages" title="" :size="drawerSize" class="tag-pages"
                   body-style=" backdrop-filter: blur(7px) brightness(88%);background-color: rgba(255, 255, 255, 0.34);border-radius: 10px">
          <div class="tag-pages">
            <ul id="top-menu-ul" class="top-menu-ul">
              <li>
                <el-image src="/static/maotou.jpg" class="logo"/>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="cosplay" to="/">
                  <span>
                    <el-icon class="custom-icon">
                      <svg t="1710869517240" class="icon" viewBox="0 0 1024 1024" version="1.1"
                           xmlns="http://www.w3.org/2000/svg" p-id="52279" width="16" height="16">
                        <path
                            d="M914.5344 463.104l-76.288-66.304c-1.3824-1.6384-3.0208-3.1232-4.864-4.2496l-288.8704-251.136c-19.1488-16.64-48.0256-16.64-67.1744 0L188.416 392.5504c-1.8432 1.1264-3.4816 2.6112-4.864 4.2496l-76.288 66.304a20.44416 20.44416 0 0 0-1.9968 28.8768 20.44416 20.44416 0 0 0 28.8768 1.9968l44.4928-38.7072v347.648c0 50.7904 41.3184 92.16 92.16 92.16h480.2048c50.7904 0 92.16-41.3696 92.16-92.16v-347.648l44.544 38.7072c3.8912 3.3792 8.6528 5.0176 13.4144 5.0176 5.7344 0 11.4176-2.4064 15.4624-7.0656 7.424-8.448 6.5024-21.4016-2.048-28.8256zM493.4656 796.672H354.2528c-31.0784 0-56.32-25.2416-56.32-56.32v-196.5568c0-14.1312 11.4688-25.6 25.6-25.6s25.6 11.4688 25.6 25.6v196.5568c0 2.816 2.304 5.12 5.12 5.12h139.2128c14.1312 0 25.6 11.4688 25.6 25.6s-11.4688 25.6-25.6 25.6z"
                            fill="#13227a" p-id="52280"></path>
                      </svg>
                    </el-icon>
                    <span class="icon-text" style="margin-left: 0">首页</span>
                  </span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="cosplay" to="/cosplay">
                  <span style="margin-left: 0">合集</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="dujia" to="/dujia">
                  <span style="margin-left: 0">独家</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="order" to="/order">
                  <span style="margin-left: 0">收藏家</span>
                </router-link>
              </li>
              <li class="depth-0">
                <router-link type="text" :href="guanhua" to="/guanhua">
                  <span style="margin-left: 0">在线看</span>
                </router-link>
              </li>
            </ul>

          </div>
        </el-drawer>

      </div>
      <div></div>
      <div class="header-banner-right">
        <div class="top-search mobile-hidden">

            <el-input v-model="searchQuery" class="search-input"
                      style="border-radius: 10px !important;" placeholder="搜索..."
                      @keyup.enter="toggleSearch"></el-input>


          <el-button type="primary" class="search-button" style="border-radius: 10px !important;" @click="toggleSearch">
            搜索
          </el-button>

        </div>
        <div class="header-user">
          <div class="login-button" v-if="!isLoggedIn">
            <el-button type="primary" style="margin-left: 16px" @click="showLoginDialog = true">登录/注册</el-button>
            <!--            <el-button class="mobile-hidden" @click="showRegisterDialog = true">快.速注册</el-button>-->
          </div>
          <div v-else class="user-info" @click="userDialog = true">
            <!--            <img src="../static/picture/tx.jpg" class="logos" alt="">-->
            <el-image :src="userInfo.avatar || '../src/static/picture/default-avatar.png'" class="logos"
                      alt=""></el-image>
          </div>
          <!-- 黑白切换按钮 -->

        </div>
        <!--        <div style="width: 30px">{{userInfo.username}}</div>-->
        <!-- 登录弹出框 -->
        <el-drawer v-model="showLoginDialog" title="登录" :size="drawerSize">
          <div class="login-box-top">
            <div class="login-logo">
              <el-image src="/static/maotou.jpg" class="logo"/>
            </div>
            <div class="login-box-bottom">
              <el-form ref="loginForm" :model="loginForm" :rules="loginRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="login">登录</el-button>
                  <el-button type="text" @click="showRegisterDialog = true">注册</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-drawer>
        <!-- 注册弹出框 -->
        <el-drawer v-model="showRegisterDialog" title="注册" :size="drawerSize">
          <div class="login-box-top">
            <div class="login-logo">
              <el-image src="../src/static/picture/soouccf956f3226f482199.jpg" class="logo"/>
            </div>
            <div class="login-box-bottom">
              <el-form ref="registerForm" :model="registerForm" :rules="registerRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="user_email">
                  <el-input v-model="registerForm.user_email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                  <el-input type="password" v-model="registerForm.confirmPassword" placeholder="请确认密码"></el-input>
                </el-form-item>
                <el-form-item label="邀请码" prop="code">
                  <el-input type="code" v-model="registerForm.code" placeholder="请输入邀请码"></el-input>
                  <el-button type="text" @click="">邀请请码就是一串密文,没有就不填！</el-button>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="register">注册</el-button>
                  <el-button type="text" @click="showRegisterDialog = false">登录</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-drawer>
        <el-drawer v-model="userDialog" title="注册" :size="drawerSize">
          <div class="main-content-right boli">
            <el-card class="boli">

              <h1>昵称：<span>{{ userInfo.username }}</span></h1>
              <p>用户等级：<span>{{ userInfo.level }}</span></p>
              <p>邮箱：<span>{{ userInfo.user_email }}</span></p>
              <p>描述：本站第<span>{{ userInfo.id }}</span>号会员 </P>
              <P>入驻时间：<span>{{ userInfo.created_at }}</span></p>
              <p>简介：<span>{{ userInfo.bio || '没有描述' }}</span></p>
            </el-card>
            <el-card class="boli">
<!--              <h3>财富</h3>-->
<!--              <p>余额：<span>￥{{ userInfo.balance }}</span></p>-->
              <p>
                积分：<span>{{ userInfo.integral }}</span>
                <el-button type="text" @click="integrals">签到</el-button>
              </p>
              <p>
                <router-link type="text" :href="users" to="/users">个人主页-></router-link>

              </p>
            </el-card>
            <el-button type="text" @click="userdelete">退出</el-button>
          </div>
        </el-drawer>
      </div>
    </div>
  </div>
</template>
<script>

import {useUserStore} from "../stores/user.js";
import {storeToRefs} from "pinia";
import {Operation} from "@element-plus/icons-vue";
import api from "@/api/api.js";
import {ElNotification} from "element-plus";
import axios from 'axios';
import guanhua from "@/pages/guanhua.vue";
import order from "@/pages/order.vue";
import dujia from "@/pages/dujia.vue";
import cosplay from "@/pages/cosplay.vue";

export default {
  components: {Operation},
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      backgroundColor: 'white',
      userStore: useUserStore(),
      lastScrollTop: 0,
      isHidden: false,
      activeIndex: '1',
      isMobileMenuVisible: false,
      searchQuery: '',
      isLoggedIn: false,
      notificationCount: 0,
      showLoginDialog: false,
      showRegisterDialog: false,
      tagpages: false,
      userDialog: false,
      loginForm: {
        username: null,
        password: null
      },
      registerForm: {
        user_email: '',
        username: '',
        password: '',
        confirmPassword: '',
        code: ''
      },
      loginRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ]
      },
      registerRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        user_email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'}
        ],
        confirmPassword: [
          {required: true, message: '请确认密码', trigger: 'blur'},
          {validator: validateConfirmPassword, trigger: 'blur'}
        ],

      }
    };
  },
  computed: {
    cosplay() {
      return cosplay
    },
    dujia() {
      return dujia
    },
    order() {
      return order
    },
    guanhua() {
      return guanhua
    },
    // ...storeToRefs(useUserStore()),
    userInfo() {
      return this.userStore.userInfo;// 从用户存储获取用户信息
    },
    drawerSize() {
      return window.innerWidth > 1000 ? '30%' : '70%';
    },
    backgroundStyle() {
      return {
        backgroundColor: this.backgroundColor === 'white' ? '#ffffff' : '#000000',
        transition: 'background-color 500ms ease-in-out',
      };
    },
  },
  methods: {
    sendCode() {
      axios.post('/api/code', {user_email: this.registerForm.user_email})
          .then(res => {
            console.log(res);
            if (res.data.code === 0) {
              ElNotification({
                title: '验证码提示',
                message: '验证码已发送，2分钟有效，不能重复发送',
                type: 'success',
              });
            } else {
              ElNotification({
                title: '验证码提示',
                message: '验证码发送失败，请稍后重试',
                type: 'error',
              });
            }
          })
          .catch(error => {
            console.log('发送验证码失败:', error);
            ElNotification({
              title: '验证码提示',
              message: '发送验证码失败，请稍后重试',
              type: 'error',
            });
          });
    },
    loadUserInfo() {
      this.userStore.loadUserInfoFromLocalStorage(); // 加载本地存储中的用户信息
    },
    checkUserInfo() {
      if (this.userInfo && Object.keys(this.userInfo).length > 0) {
        this.isLoggedIn = true; // 如果 userInfo 有值，则打开用户信息对话框
      }
    },
    toggleBackgroundColor() {
      this.backgroundColor = this.backgroundColor === 'white' ? 'black' : 'white';
    },

    userdelete() {
      this.userStore.cartch()
      this.loadUserInfo()
      this.showLoginDialog = true;
      this.userDialog = false;
      this.isLoggedIn = false;
      const currentPath = this.$route.path;

      // 如果当前路径是/users，跳转到首页
      if (currentPath === '/users') {
        this.$router.push({path: '/'});
      }
    },
    integrals() {
      api.post('/user/integral', 10)
          .then(res => {
            console.log(res);
            if (res && res.data) {
              ElNotification({
                title: '签到提示',
                message: res.data.msg,
                type: 'success',
              });

              if (res.data.code === 0) {
                this.userStore.changeUserEmail(res.data.data);
              }
            }
          })
          .catch(error => {
            console.log('签到失败:', error);
            ElNotification({
              title: '签到提示',
              message: '签到失败，请稍后重试',
              type: 'error',
            });
          });
    },
    handleScroll() {
      const currentScrollTop = window.pageYOffset || document.documentElement.scrollTop;
      if (currentScrollTop > this.lastScrollTop && currentScrollTop > 50) {
        this.isHidden = true;  // 向下滚动，隐藏导航栏
      } else {
        this.isHidden = false; // 向上滚动，显示导航栏
      }
      this.lastScrollTop = currentScrollTop;
    },
    handleResize() {
      this.$forceUpdate(); // 强制重新计算计算属性
    },
    toggletagpages() {
      this.tagpages = !this.tagpages;
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
    },
    toggleMobileMenu() {
      this.isMobileMenuVisible = !this.isMobileMenuVisible;
    },
    toggleSearch() {

      if (this.searchQuery) {
        this.search(this.searchQuery);
      } else {
        ElNotification({
          title: '搜索提示',
          message: '请输入搜索关键词',
          type: 'warning',
        });
      }
    },
    async search(query) {
      // 检查 query 是否有效
      if (!query) {
        ElNotification({
          title: '搜索提示',
          message: '请输入搜索关键词',
          type: 'warning',
        });
        return;
      }
      this.$router.push({path: '/search', query: {title: query}});
    },



    createPost() {
      // 创建帖子功能实现
    },
    viewNotifications() {
      // 查看通知功能实现
    },
    login() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          const isSuccess = await this.userStore.fetchUserInfo(this.loginForm, true); // 等待 Promise 完成
          // console.log(isSuccess, 'ssssss');
          if (isSuccess) {
            // 执行注册逻辑
            this.showRegisterDialog = false; // 设置为真使对话框显示
            this.showLoginDialog = false;
            this.isLoggedIn = true;
            console.log(this.userInfo.avatar);
          } else {
          }
        } else {
          console.log('注册失败');
          return false;
        }
      });
      console.log('登录:', this.loginForm);
      this.isLoggedIn = true;
    },
    register() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          const isSuccess = await this.userStore.fetchUserInfo(this.registerForm); // 等待 Promise 完成
          // console.log(isSuccess, 'ssssss');
          if (isSuccess) {
            // 执行注册逻辑
            this.showRegisterDialog = false; // 设置为真使对话框显示
            this.showLoginDialog = false;
            this.isLoggedIn = true;
            console.log(this.userInfo.avatar);
          } else {
          }
        } else {
          console.log('注册失败');
          return false;
        }
      });
    },
    navigateTo(url) {
      window.location.href = url;
    },
    switchToRegister() {
      this.showLoginDialog = false;
      this.showRegisterDialog = true;
    },
    switchToLogin() {
      this.showRegisterDialog = false;
      this.showLoginDialog = true;
    },
    validateConfirmPassword(rule, value, callback) {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    }
  },
  mounted() {
    this.loadUserInfo(); // 在组件加载时加载用户信息
    this.checkUserInfo(); // 在组件加载时检查用户信息
    window.addEventListener('scroll', this.handleScroll);
    window.addEventListener('resize', this.handleResize);
  }
  ,
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('resize', this.handleResize);

  }
}
;
</script>


<style scoped>
/* 添加你的样式代码 */
/* 针对小屏幕设备的样式（例如手机） */
@media (max-width: 700px) {
  .navbar {
    width: 100%;
    margin-top: 2rem;
  }

  .mobile-menu {
    display: block;
  }


  .site-header-in {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
    background-color: rgba(255, 255, 255, 0.73);

    flex-wrap: nowrap;

  }

  .header-banner-left {
    width: 50px;
    padding: inherit;
  }

  .tag-pages {
    backdrop-filter: blur(7px) brightness(88%);
    background-color: rgba(255, 255, 255, 0.34);
    border-radius: 10px
  }

  .ym-menu {
    display: none;
  }

  .top-menu-ul li {
    padding: 10px 0;
  }

  .logo {
    display: none;
  }

  .header-banner-right {
    display: flex;
  }

  .top-search {
    display: flex;
  }

  .search-input {
    width: 100%;
  }
  .header-user{
    margin-left: 5px;
  }
  .mobile-menu {
    padding: inherit;
  }
}

@media (min-width: 1250px) {

  .navbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    transition: top 0.3s;
    /* 动画效果 */
    z-index: 1000;
    /* 保证导航栏在其他元素上方 */
  //backdrop-filter: blur(10px) brightness(90%); background-color: rgba(255, 255, 255, 0.5);
  }

  .mobile-menu {
    display: none;
  }

  .hidden {
    top: -100px;
    /* 导航栏向上隐藏，需根据实际高度调整 */
  }

  .logo {
    width: 100px;
    height: 50px;
  }

  .logos {
    height: 50px;
    border-radius: 50px;
    margin: 5px 10px;
  }

  .site-header-in {
    display: flex;
    justify-content: space-around;
    align-items: center;
    height: 60px;
    padding: 0 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    flex-wrap: nowrap;
  }

  .header-banner-left {
    display: flex;
    align-items: center;
  }

  .header-banner-left .hob {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    margin-right: 10px;
  //background-color: #607d8b;
  }

  .search-input {
    margin-right: 10px;
  }

  .login-box-top {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }

  .top-search {
    display: flex;
    flex-direction: row;
    width: 250px;
  }

  .login-box-bottom {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 100%;
  }

  .header-banner-left span {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .top-menu-ul {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 60px;
    margin: 0;
    padding: 0;
    list-style: none;
  }

  .top-menu-ul li {
    position: relative;
    margin-right: 20px;
  }

  .header-banner-right {
    display: flex;
    align-items: center;

  }

  .custom-icon {
    margin-right: 0;
    /* 调整图标和文本之间的间距 */
  }

  .icon-text {
    vertical-align: middle;
    /* 使文本垂直居中对齐 */
    margin-left: 0;
  }
}

.background {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  transition: background-color 500ms ease-in-out;
}
</style>
